Module# 07: Queue                                                                            Lecture#26: Queue Using JCF

 

// Example 26.1: Creating a queue

 

/* To create a queue using PriorityQueue class along with some common operations. Queue of string objects. */

 

public class QueueCreateExample {

   public static void main(String[] args) {

      Queue<String> queue = new PriorityQueue<>();

      queue.add("one");       // Adding some elements into the queue

      queue.add("two");

      queue.add("three");

      queue.add("four");

      System.out.println(queue);    // Display the contents in queue

      queue.remove("three");

      System.out.println(queue);

      System.out.println("Queue Size: " + queue.size());

      System.out.println("Queue Contains element 'two' or not? : " +

      queue.contains("two"));

      queue.clear();          // To empty the queue

   }

}

 

 

// Example 26.2: Creating a queue using LinkedList

 

/* To create a queue using LinkedList class along with some common operations.  Queue of integer numbers. */

 

import java.util.LinkedList;

import java.util.Queue;

 

public class QueueCreateLinkedList {

     public static void main(String[] args)  {

      // Declaration of a queue using LinkedList class

      Queue<Integer> q = new LinkedList<Integer>();

      // Adds elements {0, 1, 2, 3, 4} to queue

      for(int i=0; i<5; i++)

          q.add(i);

      // Display contents of the queue.

      System.out.println("The queue contains :"+q);

  // Continued on...

      // To remove the head of queue.

      int x = q.remove();

      System.out.println("The element deleted :"+ x);

      System.out.println(q);

      // To view the head of queue

      int head = q.peek();

      System.out.println("head of queue:"+ head);

      // The size of the queue

      int size = q.size();

      System.out.println("Size of queue: "+ size);

    }

}

 

// Example 26.3: Inserting element into a queue

 

/* To create queue structure with ArrayBlocking class (same as PriorotyQueue class) and insert elements and queue structure grows automatically. */

 

import java.util.concurrent.*;

 

public class QueueInsertOperation1 {

   public static void main(String[] args) {

      BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(2);

      System.out.println(queue.add(1));

      System.out.println(queue.add(2));  // Maximum capacity

      System.out.println(queue);

      System.out.println(queue.add(3));  // Queue grows dynamically

      System.out.println(queue);

      for(int i=9; i>0; i--)        // Add more … to the queue

          queue.add(i);             //Queue grows further dynamically

      System.out.println(queue);

   }

}

 

// Example 26.4: Inserting element into queue

 

/* Like the add(), the Queue interface has the offer() operation, which is also used to insert new element into the queue. If it performs insert operation successfully, it returns “true” value. Otherwise, it returns “false” value. The following program demonstrate this functionality. */

 

import java.util.concurrent.*;

 

public class QueueInsertOperation2 {

   public static void main(String[] args) {

      BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);

      System.out.println(queue.offer("One"));

      System.out.println(queue.offer("Two"));

      System.out.println(queue);

      System.out.println(queue.offer("Nine"));

      System.out.println(queue);

   }

}

 

// Example 26.5: Removing element from queue

 

// Java Queue delete operations with remove() method

 

import java.util.*;

 

public class QueueRemoveOperation{

    public static void main(String[] args)  {        

      Queue<String> queue = new LinkedList<String>();

      queue.offer("One");

      queue.offer("Two");          

     System.out.println(queue);         

      System.out.println(queue.remove());

      System.out.println(queue.remove());      

      System.out.println(queue.remove());       // Throws an exception     

    }

}

 

Example 26.6: Delete operations with poll() method

 

/* The poll() operation is used to delete an element from the head of the queue. If it performs delete operation successfully, it returns the head element of the queue. Otherwise it returns “null” value. */

 

import java.util.*;

 

public class QueuePollOperation{

    public static void main(String[] args) {         

      Queue<String> queue = new LinkedList<String>();

      queue.offer("One");

      queue.offer("Two");          

      System.out.println(queue);         

      System.out.println(queue.poll());

      System.out.println(queue.poll());        

      System.out.println(queue.poll());      // It returns “null”

   }

}

 

// Example 26.7: Queue with user-defined objects

 

import java.util.*;

 

class Book implements Comparable<Book>{ 

     int bookId; 

     String name;

     String author;

     String publisher; 

     int quantity;

     public Book(int id, String name, String author, String pub, int qty) { 

                  bookId = id; 

                  this.name = name; 

                  this.author = author; 

                  publisher = pub; 

                  quantity  = qty; 

      }

      // Methods under this class are defined next

      // Defining the compareTo() method

      public int compareTo(Book b) { 

            if(bookId>b.bookId) 

                 return 1; 

            else

                      if(bookId<b.bookId) 

                     return -1; 

                 else 

                   return 0; 

                    

      } 

  } // End of class Book

 

// The main program is given below...

 

public class QueueCreateDemo { 

     public static void main(String[] args) { 

      PriorityQueue<Book> queue=new PriorityQueue<Book>(); 

      //Creating Books 

      Book b1=new Book(111,"Joy with Java","Debasis Samanta","Elsevier",8); 

      Book b2=new Book(222,"Complete Java","Herbert Schildt","Oracle",6); 

      Book b3=new Book(333,"Headstart Java","Forouzan","O’Reilly",4); 

      //Adding Books to the queue 

      queue.add(b1); 

      queue.add(b2); 

      queue.add(b3); 

      System.out.println("Traversing the queue elements:"); 

      //Traversing queue with for-each loop

      for(Book b:queue){ 

           System.out.println(b.bookId+" "+b.name+" "+b.author+" "+b.publisher +""+b.quantity); 

          }

 

 

     // Removing a book from the queue

     queue.remove(); 

     System.out.println("After removing one book record:");

      // Adding another book into the queue

     queue.add(new Book(555, "Classic Data Structures", "D. Samanta", "Prentice Hall", 9));

 

      for(Book b:queue){ 

                System.out.println(b.bookId+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity); 

          }

 

     }

}

 

// Example 26.8: Copying an array of objects to a queue

 

/* To convert a Java array to Queue using addAll() method defined in the Collection class. */

 

import java.util.*;

 

public class ArrayToQueue {

    public static void main(String[] args) {

      // Create an array of String objects     

      String city[] = {"CCU","DEL","BLR","MUM","GAU"};

      // Declare a queue

      Queue<String> queue = new PriorityQueue<String>();

      // Copying the array to Queue

      Collections.addAll(queue, city);

      // Printing the array

      System.out.println("Array :" + city);

      System.out.println();

      // Printing the queue

      System.out.println("Queue :" + queue);

   }

}

 

// Example 26.9: Copying a queue to an array

 

/* To copy a Queue object to an array using toArray method defined in the Collection class. */

 

import java.util.*;

 

public class QueueToArray {

    public static void main(String[] args) {

      Queue<String> queue = new LinkedList<String>(); // Creating a queue

      queue.add(”Jio");

      queue.add("123");

      queue.add("John");

      queue.add("Jaya");

      queue.add("Jim");

      queue.add("!@#$%");

      // Copying the queue to an array of string objects

      String city[] = queue.toArray(new String[queue.size()]);

      System.out.println(Arrays.toString(city)); // Printing the array

      System.out.println();

      System.out.println("Queue :" + queue); // Printing the queue

    }

}

 

// Example 26.10: Accessing an element in a queue using element()

 

/* There are two methods in Queue interface: element() and peek(), which are used to access an element in a queue. Following two examples illustrates the working of the two methods. This is an example of accessing with element() method. */

 

import java.util.*;

 

public class QueueElementAccess {

    public static void main(String[] args) {

      Queue<String> queue = new LinkedList<String>();

      queue.add("One");

      System.out.println(queue.element());

      System.out.println(queue);

      queue.clear();

      System.out.println(queue.element()); // Throws an exception

   }

}

 

// Example 26.11: Accessing an element in a queue using peek()

 

/* Queue.peek(): The peek() operation is used to retrieve an element from the head of the queue, without removing it. If it performs the operation successfully, it returns the head element of the queue. Otherwise, it returns null value. */

 

import java.util.*;

 

public class QueuePeekOperation {

   public static void main(String[] args) {

      Queue<String> queue = new LinkedList<String>();

      queue.add("One");

      System.out.println(queue.peek());

      System.out.println(queue);

      queue.clear();

      System.out.println(queue.peek()); // Returns null value

   }

}

 

// Example 26.12: ArrayDeque by using a stack

 

import java.util.*;

 

class ArrayDequeDemo {

  public static void main(String args[]) {

      // Create an array deque.

  ArrayDeque<String>adq = new ArrayDeque<String>();

  adq.push("A");// Use an ArrayDeque like a stack.

  adq.push("B");

  adq.push("D");

  adq.push("E");

  adq.push("F");

  System.out.print("Popping the stack: ");

  while(adq.peek() != null)

       System.out.print(adq.pop() + " ");

  System.out.println();

   }

}